{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "454a9d35",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/llm/Konko.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a07f0af-6f8b-4a4e-a984-5f0f161dd0c3",
   "metadata": {},
   "source": [
    "# Konko"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "1d8bff34",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙.\n",
    "\n",
    ">[Konko](https://www.konko.ai/) API is a fully managed Web API designed to help application developers:\n",
    "\n",
    "Konko API is a fully managed API designed to help application developers:\n",
    "\n",
    "1. Select the right LLM(s) for their application\n",
    "2. Prototype with various open-source and proprietary LLMs\n",
    "3. Access Fine Tuning for open-source LLMs to get industry-leading performance at a fraction of the cost\n",
    "4. Setup low-cost production APIs according to security, privacy, throughput, latency SLAs without infrastructure set-up or administration using Konko AI's SOC 2 compliant, multi-cloud infrastructure\n",
    "\n",
    "### Steps to Access Models\n",
    "1. **Explore Available Models:** Start by browsing through the [available models](https://docs.konko.ai/docs/list-of-models) on Konko. Each model caters to different use cases and capabilities.\n",
    "\n",
    "2. **Identify Suitable Endpoints:** Determine which [endpoint](https://docs.konko.ai/docs/list-of-models#list-of-available-models) (ChatCompletion or Completion) supports your selected model.\n",
    "\n",
    "3. **Selecting a Model:** [Choose a model](https://docs.konko.ai/docs/list-of-models#list-of-available-models) based on its metadata and how well it fits your use case.\n",
    "\n",
    "4. **Prompting Guidelines:** Once a model is selected, refer to the [prompting guidelines](https://docs.konko.ai/docs/prompting) to effectively communicate with it.\n",
    "\n",
    "5. **Using the API:** Finally, use the appropriate Konko [API endpoint](https://docs.konko.ai/docs/quickstart-for-completion-and-chat-completion-endpoint) to call the model and receive responses.\n",
    "\n",
    "To run this notebook, you'll need Konko API key. You can create one by signing up on [Konko](https://www.konko.ai/).\n",
    "\n",
    "This example goes over how to use LlamaIndex to interact with `Konko` ChatCompletion [models](https://docs.konko.ai/docs/list-of-models#konko-hosted-models-for-chatcompletion) and Completion [models](https://docs.konko.ai/docs/list-of-models#konko-hosted-models-for-completion)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb0d15f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-konko"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f4e41f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3907f07b-a33a-46db-b799-fec83843ff60",
   "metadata": {},
   "source": [
    "## Call `chat` with ChatMessage List\n",
    "You need to set env var `KONKO_API_KEY`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0bec6d7-d5cc-4c23-aa95-a915e65220cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"KONKO_API_KEY\"] = \"<your-api-key>\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02bfb427-2607-4322-bdaa-f012a87a0112",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.konko import Konko\n",
    "from llama_index.core.llms import ChatMessage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1135fe2a-b4ff-4352-a825-bdc3aca17b60",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant:   The Big Bang Theory is the leading explanation for the origin and evolution of the universe, based on a vast body of observational and experimental evidence. Here's a brief summary of the theory:\n",
      "\n",
      "1. The universe began as a single point: According to the Big Bang Theory, the universe began as an infinitely hot and dense point called a singularity around 13.8 billion years ago.\n",
      "2. Expansion and cooling: The singularity expanded rapidly, and as it did, it cooled and particles began to form. This process is known as the \"cosmic microwave background radiation\" (CMB).\n",
      "3. Formation of subatomic particles: As the universe expanded and cooled, protons, neutrons, and electrons began to form from the CMB. These particles eventually coalesced into the first atoms, primarily hydrogen and helium.\n",
      "4. Nucleosynthesis: As the universe continued to expand and cool, more complex nuclei were formed through a process called nucleosynthesis. This process created heavier elements such as deuterium, helium-3, helium-4, and lithium.\n",
      "5. The first stars and galaxies: As\n"
     ]
    }
   ],
   "source": [
    "llm = Konko(model=\"meta-llama/llama-2-13b-chat\")\n",
    "messages = ChatMessage(role=\"user\", content=\"Explain Big Bang Theory briefly\")\n",
    "\n",
    "resp = llm.chat([messages])\n",
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6bc1e74f",
   "metadata": {},
   "source": [
    "## Call `chat` with OpenAI Models\n",
    "You need to either set env var `OPENAI_API_KEY`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b25f46e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"<your-api-key>\"\n",
    "\n",
    "llm = Konko(model=\"gpt-3.5-turbo\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c4ec4a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant: The Big Bang Theory is a scientific explanation for the origin and evolution of the universe. According to this theory, the universe began as a singularity, an extremely hot and dense point, approximately 13.8 billion years ago. It then rapidly expanded and continues to expand to this day. As the universe expanded, it cooled down, allowing matter and energy to form. Over time, galaxies, stars, and planets formed through gravitational attraction. The Big Bang Theory is supported by various pieces of evidence, such as the observed redshift of distant galaxies and the cosmic microwave background radiation.\n"
     ]
    }
   ],
   "source": [
    "message = ChatMessage(role=\"user\", content=\"Explain Big Bang Theory briefly\")\n",
    "resp = llm.chat([message])\n",
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0515c6b2-e691-4f89-baa2-4964abee9cc5",
   "metadata": {},
   "source": [
    "### Streaming"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "099f51ad-d585-4bf4-b0e1-95ed7ecf3f85",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Once upon a time in a small village, there lived a young girl named Lily. She was known for her kind heart and love for animals. Every day, she would visit the nearby forest to feed the birds and rabbits.\n",
      "\n",
      "One sunny morning, as Lily was walking through the forest, she stumbled upon a wounded bird with a broken wing. She carefully picked it up and decided to take it home. Lily named the bird Ruby and made a cozy nest for her in a small cage.\n",
      "\n",
      "Days turned into weeks, and Ruby's wing slowly healed. Lily knew it was time to set her free. With a heavy heart, she opened the cage door, and Ruby hesitantly flew away. Lily watched as Ruby soared high into the sky, feeling a sense of joy and fulfillment.\n",
      "\n",
      "As the years passed, Lily's love for animals grew stronger. She started rescuing and rehabilitating injured animals, creating a sanctuary in the heart of the village. People from far and wide would bring her injured creatures, knowing that Lily would care for them with love and compassion.\n",
      "\n",
      "Word of Lily's sanctuary spread, and soon, volunteers came forward to help her. Together, they built enclosures, planted trees, and created a safe haven for all creatures big and small. Lily's sanctuary became a place of hope and healing, where animals found solace and humans learned the importance of coexistence.\n",
      "\n",
      "Lily's dedication and selflessness inspired others to follow in her footsteps. The village transformed into a community that valued and protected its wildlife. Lily's dream of a harmonious world, where humans and animals lived in harmony, became a reality.\n",
      "\n",
      "And so, the story of Lily and her sanctuary became a legend, passed down through generations. It taught people the power of compassion and the impact one person can have on the world. Lily's legacy lived on, reminding everyone that even the smallest act of kindness can create a ripple effect of change."
     ]
    }
   ],
   "source": [
    "message = ChatMessage(role=\"user\", content=\"Tell me a story in 250 words\")\n",
    "resp = llm.stream_chat([message], max_tokens=1000)\n",
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac92c80f-5b82-4143-a6f9-549d6f5dfa70",
   "metadata": {},
   "source": [
    "## Call `complete` with Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1290c9b1-3c37-4db0-aa94-dda1c90d4f8b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " MAX(capacity) FROM stadiumm</s>\n"
     ]
    }
   ],
   "source": [
    "llm = Konko(model=\"numbersstation/nsql-llama-2-7b\", max_tokens=100)\n",
    "text = \"\"\"CREATE TABLE stadium (\n",
    "    stadium_id number,\n",
    "    location text,\n",
    "    name text,\n",
    "    capacity number,\n",
    "    highest number,\n",
    "    lowest number,\n",
    "    average number\n",
    ")\n",
    "\n",
    "CREATE TABLE singer (\n",
    "    singer_id number,\n",
    "    name text,\n",
    "    country text,\n",
    "    song_name text,\n",
    "    song_release_year text,\n",
    "    age number,\n",
    "    is_male others\n",
    ")\n",
    "\n",
    "CREATE TABLE concert (\n",
    "    concert_id number,\n",
    "    concert_name text,\n",
    "    theme text,\n",
    "    stadium_id text,\n",
    "    year text\n",
    ")\n",
    "\n",
    "CREATE TABLE singer_in_concert (\n",
    "    concert_id number,\n",
    "    singer_id text\n",
    ")\n",
    "\n",
    "-- Using valid SQLite, answer the following questions for the tables provided above.\n",
    "\n",
    "-- What is the maximum capacity of stadiums ?\n",
    "\n",
    "SELECT\"\"\"\n",
    "response = llm.complete(text)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be1a7fe6-51b7-4e80-b60d-fbe3335610c7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "```cpp\n",
      "#include<iostream>\n",
      "using namespace std;\n",
      "\n",
      "// Node structure\n",
      "struct Node {\n",
      "    int data;\n",
      "    Node* next;\n",
      "};\n",
      "\n",
      "// Class for LinkedList\n",
      "class LinkedList {\n",
      "    private:\n",
      "        Node* head;\n",
      "    public:\n",
      "        LinkedList() : head(NULL) {}\n",
      "\n",
      "        void addNode(int n) {\n",
      "            Node* newNode = new Node;\n",
      "            newNode->data = n;\n",
      "            newNode->next = head;\n",
      "            head = newNode;\n",
      "        }\n",
      "\n",
      "        void printList() {\n",
      "            Node* cur = head;\n",
      "            while(cur != NULL) {\n",
      "                cout << cur->data << \" -> \";\n",
      "                cur = cur->next;\n",
      "            }\n",
      "            cout << \"NULL\" << endl;\n",
      "        }\n",
      "};\n",
      "\n",
      "int main() {\n",
      "    LinkedList list;\n",
      "    list.addNode(1);\n",
      "    list.addNode(2);\n",
      "    list.addNode(3);\n",
      "    list.printList();\n",
      "\n",
      "    return 0;\n",
      "}\n",
      "```\n",
      "\n",
      "This program creates a simple linked list with a `Node` structure and a `LinkedList` class. The `addNode` function is used to add nodes to the list, and the `printList` function is used to print the list. The main function creates a `LinkedList` object, adds some nodes, and then prints the list.</s>"
     ]
    }
   ],
   "source": [
    "llm = Konko(model=\"phind/phind-codellama-34b-v2\", max_tokens=100)\n",
    "text = \"\"\"### System Prompt\n",
    "You are an intelligent programming assistant.\n",
    "\n",
    "### User Message\n",
    "Implement a linked list in C++\n",
    "\n",
    "### Assistant\n",
    "...\"\"\"\n",
    "\n",
    "resp = llm.stream_complete(text, max_tokens=1000)\n",
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc3a2018-89f1-4795-9b68-c06b8f104a69",
   "metadata": {},
   "source": [
    "## Model Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88c2680d-5e21-4eba-a685-a30d64554b14",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = Konko(model=\"meta-llama/llama-2-13b-chat\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24ebd16b-1740-4f31-800d-9c9c8fcc0d96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Sure, here's an example of how you can send a request to an HTTP server using C++:\n",
      "\n",
      "First, you'll need to include the `iostream` and `string` headers:\n",
      "```\n",
      "#include <iostream>\n",
      "#include <string>\n",
      "```\n",
      "Next, you'll need to use the `std::string` class to create a string that contains the HTTP request. For example, to send a GET request to the server, you might use the following code:\n",
      "```\n",
      "std::string request = \"GET /path/to/resource HTTP/1.1\\r\\n\";\n",
      "request += \"Host: www.example.com\\r\\n\";\n",
      "request += \"User-Agent: My C++ HTTP Client\\r\\n\";\n",
      "request += \"Accept: */*\\r\\n\";\n",
      "request += \"Connection: close\\r\\n\\r\\n\";\n",
      "```\n",
      "This code creates a string that contains the GET request, including the request method, the URL, and the HTTP headers.\n",
      "\n",
      "Next, you'll need to create a socket using the `socket` function:\n",
      "```\n",
      "int sock = socket(AF_INET, SOCK_STREAM, 0);\n",
      "```\n",
      "This function creates a socket that can be used to send and receive data over the network.\n",
      "\n",
      "Once you have a socket, you can send the request to the server using the `send` function:\n",
      "```\n",
      "send(sock, request.c_str(), request.size(), 0);\n",
      "```\n",
      "This function sends the request to the server over the socket. The `c_str` method returns a pointer to the string's data, which is passed to the `send` function. The `size` method returns the length of the string, which is also passed to the `send` function.\n",
      "\n",
      "Finally, you'll need to read the response from the server using the `recv` function:\n",
      "```\n",
      "char buffer[1024];\n",
      "int bytes_received = recv(sock, buffer, 1024, 0);\n",
      "```\n",
      "This function reads data from the server and stores it in the `buffer` array. The `bytes_received` variable is set to the number of bytes that were received.\n",
      "\n",
      "Here's the complete code:\n",
      "```\n",
      "#include <iostream>\n",
      "#include <string>\n",
      "#include <sys/socket.h>\n",
      "#include <netinet/in.h>\n",
      "#include <arpa/inet.h>\n",
      "\n",
      "int main() {\n",
      "  // Create a socket\n",
      "  int sock = socket(AF_INET, SOCK_STREAM, 0);\n",
      "\n",
      "  // Create a string that contains the HTTP request\n",
      "  std::string request = \"GET /path/to/resource HTTP/1.1\\r\\n\";\n",
      "  request += \"Host: www.example.com\\r\\n\";\n",
      "  request += \"User-Agent: My C++ HTTP Client\\r\\n\";\n",
      "  request += \"Accept: */*\\r\\n\";\n",
      "  request += \"Connection: close\\r\\n\\r\\n\";\n",
      "\n",
      "  // Send the request to the server\n",
      "  send(sock, request.c_str(), request.size(), 0);\n",
      "\n",
      "  // Read the response from the server\n",
      "  char buffer[1024];\n",
      "  int bytes_received = recv(sock, buffer, 1024, 0);\n",
      "\n",
      "  // Print the response\n",
      "  std::cout << \"Response: \" << buffer << std::endl;\n",
      "\n",
      "  // Close the socket\n",
      "  close(sock);\n",
      "\n",
      "  return 0;\n",
      "}\n",
      "```\n",
      "This code sends a GET request to the server, reads the response, and prints it to the console. Note that this is just a simple example, and in a real-world application you would probably want to handle errors and manage the socket more robustly."
     ]
    }
   ],
   "source": [
    "resp = llm.stream_complete(\n",
    "    \"Show me the c++ code to send requests to HTTP Server\", max_tokens=1000\n",
    ")\n",
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
